﻿using AppDataStruct;
using LogLib;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace EECMISWS
{
    internal partial class WSClient
    {
        private OfficialInfo _officialInfo = new OfficialInfo();
        public OfficialInfo Official
        {
            private set { _officialInfo = value; }
            get { return _officialInfo; }
        }

        private void SaveOfficialInfo(OfficialInfo info)
        {
            string msg = "";
            bool bRet = Data2Xml.Class2File(info, BaseDirectory + "OfficialInfo.xml", out msg);
            if (!bRet)
            { 
                Log.WriteAsync("保存OfficialInfo失败:" + msg);
            }
        }
        /// <summary>
        /// 核查是否是国家工作人员
        /// </summary>
        /// <param name="nERRCode"></param>
        /// <param name="sfzh">身份证号码</param>
        /// <returns></returns>
        public bool QueryOfficial(string sfzh, string xm,string xb,string csrq,ref bool isOfficial)
        {
            _returnInfo.Reset();
            _officialInfo.Reset();
            JObject jsonResult = new JObject();
            // 1、身份证+姓名+性别+出生日期,传了姓名、性别、出生日期，就会查出疑似工作人员的
            JObject Args = new JObject();
            Args.Add("sfzh", sfzh);
            Args.Add("xb", xb);
            Args.Add("csrq", csrq);
            Args.Add("zwxm", xm);
            //string strDw = ClientConfig.TBDWBH.Substring(0, 2);
            //if (strDw == "43" || strDw == "36" || strDw == "22")//湖南江西吉林
            //{
            //    Args.Add("sfzh", sfzh);
            //}
            //else
            //{
            //    Args.Add("sfzh", sfzh);
            //    Args.Add("zwxm", _personInfo.XM);
            //    Args.Add("xb", _personInfo.XB);
            //    Args.Add("csrq", _personInfo.CSRQ);
            //}
            try
            {
                string json = Args.ToString();
                _returnInfo = CallUnimethod(funcQueryOfficial, json, true);
                if (!_returnInfo.CallSuccessed)
                {
                    _strMessage = _returnInfo.ExceptionString;
                    return false;
                }
                if (_returnInfo.ErrorCode == "CRJ1002") //登录失败
                {
                    if (Login())
                    {
                        _returnInfo = CallUnimethod(funcQueryOfficial, json, true);
                    }
                    else
                    {
                        return false;
                    }
                }
                if (!_returnInfo.CallSuccessed)
                {
                    _returnInfo.CustomCode = 444;
                    _strMessage = _returnInfo.ExceptionString;
                    return false;
                }
                if (!_returnInfo.Success)
                {
                    _returnInfo.CustomCode = 444;
                    _strMessage = string.Format("接口查询错误.\n 详情: 返回代码{0},{1}",
                        _returnInfo.ErrorCode,
                        _returnInfo.Message); ;
                    return false;
                }

                //非国家工作人员
                if (string.IsNullOrEmpty(_returnInfo.DataContent))
                {
                    _returnInfo.CustomCode = 0;
                    isOfficial = false;
                    Log.WriteAsync("不是国家工作人员: " + _returnInfo.Message);
                    return true;
                }
                else
                {
                    JArray jArray = JArray.Parse(_returnInfo.DataContent);
                    if (jArray.Count <= 0)
                    {
                        _returnInfo.CustomCode = 0;
                        isOfficial = false;
                        Log.WriteAsync("不是国家工作人员");
                        return true;
                    }
                    else //此人为国家工作人员
                    {
                        _returnInfo.CustomCode = 723;
                        isOfficial = true;
                        _officialInfo.ZWXM = jArray[0]["zwxm"].ToString();//中文姓名
                        _officialInfo.RSZGDW = jArray[0]["rszgdw"].ToString();//人事主管单位
                        _strMessage = string.Format("查询到是国家工作人员.\n 中文姓名:{0}. \n 人事主管单位: {1}.", _officialInfo.ZWXM, _officialInfo.RSZGDW);
                        Log.WriteAsync(_strMessage);
                        SaveOfficialInfo(_officialInfo);
                        return true;
                    }
                }
            }
            catch (ThreadAbortException ex)
            {
                ResetWebServiceClient();
                Log.WriteException(ex.ToString());
                return false;
            }
            catch (Exception ex)
            {
                _returnInfo.CustomCode = 444;
                Log.WriteException(ex.ToString());
                _strMessage = "程序代码运行发生了异常: " + ex.Message;
                Log.WriteAsync(_strMessage);
                return false;
            }
        }

        /// <summary>
        /// 查询受控对象
        /// </summary>
        /// <param name="sfzh"></param>
        /// <param name="isInSpecialList"></param>
        /// <returns></returns>
        public bool QueryCheckSpecialList(string sfzh, ref bool isInSpecialList)
        {
            JObject Args = new JObject();
            try
            {
                //  1、人员类别为R内地居民：
                //   ①中文姓名+性别+出生日期+身份证号码 
                //   ②证件号码+证件种类
                //   ③中文姓名+出生日期+性别+身份证号码+证件号码+证件种类
                //string strDw = ClientConfig.TBDWBH.Substring(0, 2);
                Args.Add("rylb", "R");
                Args.Add("sfzh", sfzh);
                string json = Args.ToString();
                _returnInfo.Reset();
                _returnInfo = CallUnimethod(funcCheckSpecialList, json, true);
                //if ("33" == this.DWBH.Substring(0, 2))//浙江查控接口
                //{
                //    _returnInfo = CallUnimethod("kz_checkSpecialListLabel", json, true);
                //}
            
                if (!_returnInfo.CallSuccessed)
                {
                    _returnInfo.CustomCode = 444;
                    _strMessage = _returnInfo.ExceptionString;
                    return false;
                }
                if (!_returnInfo.Success)
                {
                    _strMessage = string.Format("接口查询错误.\n 详情: 返回代码{0},{1}",
                        _returnInfo.ErrorCode,
                        _returnInfo.Message); ;
                    return false;
                }

                if (string.IsNullOrEmpty(_returnInfo.DataContent))
                {
                    _returnInfo.CustomCode = 444;
                    _strMessage = "查询失败: 无法解析的空数据!";
                    return false;
                }
                JObject jData = JObject.Parse(_returnInfo.DataContent);
                string strIsKZ = jData["sfkzdx"].ToString();//1:是控制对象， 0:非控制对象
                if ("1" == strIsKZ) //是控制对象
                {
                    _returnInfo.CustomCode = 721;
                    isInSpecialList = true;
                    if (jData["kzlx"] != null)               //浙江必须把控制类型进行一次代码转换,返回到界面
                    {
                        string strKZLX = jData["kzlx"].ToString();//控制类型，浙江特有受控
                        string strLog = string.Format("此人为控制对象:{0}, 受控类型: {1}",
                            strKZLX,
                            GetKZLX_Code(strKZLX));
                        Log.WriteAsync(strLog);
                    }
                    else
                    {
                        _returnInfo.CustomCode = 721;
                        string strLog = "此人为未知控制对象721";
                        Log.WriteAsync(strLog);
                    }
                    return true;
                }
                else if ("0" == strIsKZ) //非受控人员
                {
                    _returnInfo.CustomCode = 0;
                    isInSpecialList = false;
                    Log.WriteAsync("不是控制对象");
                    return true;
                }
                else //未知代码，此人为控制对象
                {
                    isInSpecialList = true;
                    _returnInfo.CustomCode = 722;
                    string strLog = string.Format("未知代码:{0}, 此人为控制对象", strIsKZ);
                    Log.WriteAsync(strLog);
                    return true;
                }
            }
            catch (ThreadAbortException ex)
            {
                ResetWebServiceClient();
                Log.WriteException(ex.ToString());
                return false;
            }
            catch (Exception ex)
            {
                _returnInfo.CustomCode = 444;
                Log.WriteException(ex.ToString());
                _strMessage = "程序代码运行发生了异常: " + ex.Message;
                Log.WriteAsync(_strMessage);
                return false;
            }
        }

        /// <summary>
        /// 是否在大陆境内
        /// </summary>
        /// <param name="nERRCode"></param>
        /// <param name="sfzh">身份证号码</param>
        /// <returns>-1：查询失败，0-境外，1-境内，2-无出境记录</returns>
        public bool CheckInDomestic(string sfzh, ref bool NotInMainland)
        {
            int state = -1;
            _returnInfo.Reset();
            try
            {
                string startDateStr = DateTime.Now.AddYears(-1).ToString("yyyyMMdd");
                JObject Args = new JObject();
                Args.Add("sfzh", sfzh);
                Args.Add("personType", "2");//2 非港澳居民
                Args.Add("startDate", startDateStr);//开始日期，结束日期默认到今天

                string json = Args.ToString();
                _returnInfo = CallUnimethod(funcCheckInDomestic, json, true);
                if (_returnInfo.ErrorCode == "CRJ1002") //登录失败
                {
                    Thread.Sleep(500);
                    if (Login())
                    {
                        _returnInfo = CallUnimethod(funcCheckInDomestic, json, true);
                    }
                    else
                    {
                        _returnInfo.CustomCode = 444;
                        state = -1;
                        return false;
                    }
                }
                if (!_returnInfo.CallSuccessed)
                {
                    state = -1;
                    _returnInfo.CustomCode = 444;
                    _strMessage = _returnInfo.ExceptionString;
                    return false;
                }
                if (!_returnInfo.Success)
                {
                    _returnInfo.CustomCode = 444;
                    _strMessage = string.Format("接口{0}调用发生了错误.\n 详情: 返回代码{1},{2}",
                        funcCheckInDomestic,
                        _returnInfo.ErrorCode,
                        _returnInfo.Message);
                    state = -1;
                    return false;
                }
                JObject jObj = JObject.Parse(_returnInfo.DataContent);
                string strInfo = jObj["inmainland"].ToString();
                if (string.IsNullOrEmpty(strInfo))
                {
                    _returnInfo.CustomCode = 444;
                    state = -1;
                    _strMessage = string.Format("接口{0}返回空数据!", funcCheckInDomestic);
                    return false;
                }
                else
                {
                    state = Convert.ToInt32(strInfo);
                    if (state == 0)
                    {
                        _strMessage = string.Format("是否在境内查询结果: {0}, 在境外", state);
                        NotInMainland = true;
                        _returnInfo.CustomCode = 724;
                    }
                    else if (state == 1)
                    {
                        _strMessage = string.Format("是否在境内查询结果: {0}, 在境内", state);
                        _returnInfo.CustomCode = state;
                        NotInMainland = false;
                    }
                    else
                    {
                        _strMessage = string.Format("是否在境内查询结果: {0}, 无出境记录", state);
                        _returnInfo.CustomCode = state;
                        NotInMainland = false;
                    }
                    Log.WriteAsync(_strMessage);
                    return true;
                }
            }
            catch (ThreadAbortException ex)
            {
                ResetWebServiceClient();
                Log.WriteException(ex.ToString());
                return false;
            }
            catch (System.Exception ex)
            {
                Log.WriteException(ex.ToString());
                _strMessage = "程序代码运行发生了异常: " + ex.Message;
                Log.WriteAsync(_strMessage);
                return false;
            }
        }

        public bool CheckMZ(out bool isBZCJ)
        {
            isBZCJ = false;
            _returnInfo.Reset();
            if (!string.IsNullOrEmpty(_personInfo.MZ_CODE))
            {
                if (_forbiddenNations.ContainsKey(_personInfo.MZ_CODE))
                {
                    _returnInfo.CustomCode = 741;
                    isBZCJ = true;
                    _strMessage = string.Format("受控的民族代码: {0}", _personInfo.MZ_CODE);
                    Log.WriteAsync(_strMessage);
                    return true;
                }
                else
                {
                    _returnInfo.CustomCode = 0;
                    isBZCJ = false;
                    _strMessage = string.Format("可以出境的民族代码: {0}", _personInfo.MZ_CODE);
                    Log.WriteAsync(_strMessage);
                    return true;
                }
            }
            if (string.IsNullOrEmpty(_personInfo.MZ_CODE) && string.IsNullOrEmpty(_personInfo.MZ))
            {
                isBZCJ = true;
                _returnInfo.CustomCode = 707;
                _strMessage = "民族信息为空: " + _personInfo.SFZH;
                Log.WriteAsync(_strMessage);
                return true;
            }
            if (_personInfo.MZ.Contains("族"))
            {
                int pos = _personInfo.MZ.IndexOf("族");
                _personInfo.MZ = _personInfo.MZ.Substring(0, pos);
            }
            if (!Nations.ContainsValue(_personInfo.MZ))
            {
                _returnInfo.CustomCode = 444;
                _strMessage = string.Format("非法的民族: {0}", _personInfo.MZ);
                Log.WriteAsync(_strMessage);
                return false;
            }

            if (_forbiddenNations.ContainsValue(_personInfo.MZ))
            {
                _returnInfo.CustomCode = 741;
                isBZCJ = true;
                _strMessage = string.Format("受控的民族: {0}", _personInfo.MZ);
                Log.WriteAsync(_strMessage);
            }
            else
            {
                _returnInfo.CustomCode = 0;
                isBZCJ = false;
            }
            return true;
        }

        /// <summary>
        /// 控制对象查询
        /// </summary>
        /// <param name="sfzh"></param>身份证号
        /// <returns></returns>
        public string GetKZLX_Code(string strKZLX)
        {
            if ("13" == strKZLX)        //不准出境人员
                return "725";
            else if ("15" == strKZLX)   //在逃人员
                return "726";
            else if ("16" == strKZLX)   //违规人员
                return "727";
            else if ("17" == strKZLX)   //特许备案
                return "728";
            else if ("18" == strKZLX)   //内控
                return "729";
            else
                return "721";
        }
    }
}
